import {defineStore} from 'pinia';
import {updateElementPlusTheme, resetElementPlusTheme} from "@/layouts/utils/switchTheme";

const orginalThemeColorOptions = [
    {
        label: '主题色',
        name: 'primary',
        color: '#409eff',
    },
    {
        label: '信息色',
        name: 'info',
        color: '#909399',
    },
    {
        label: '成功色',
        name: 'success',
        color: '#67c23a',
    },
    {
        label: '警告色',
        name: 'warning',
        color: '#e6a23c',
    },
]

export const useThemeStore = defineStore('theme', {
    state: () => ({
        theme: localStorage.getItem('theme') || 'light',
        themeColorOptions: JSON.parse(localStorage.getItem('themeColorOptions')) || JSON.parse(JSON.stringify(orginalThemeColorOptions))
    }),

    actions: {
        // 切换主题
        toggleTheme() {
            this.theme = this.theme === 'light' ? 'dark' : 'light';
            this.setTheme(this.theme);
            resetElementPlusTheme(this.theme);
            this.setThemeColor();
        },

        // 设置主题
        setTheme(theme) {
            this.theme = theme;
            if (this.theme === 'dark') {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
            localStorage.setItem('theme', this.theme);
            resetElementPlusTheme(this.theme);
            this.setThemeColor();
        },

        // 设置主题颜色
        setThemeColor() {
            if (localStorage.getItem('themeColorOptions')) {
                this.themeColorOptions.forEach(item => {
                    this.updateThemeColor(item)
                })
            }
        },

        // 更新颜色配置
        updateThemeColor(item) {
            updateElementPlusTheme(item.name, item.color)
            localStorage.setItem('themeColorOptions', JSON.stringify(this.themeColorOptions));
        },

        // 重置颜色配置
        resetThemeColor() {
            this.themeColorOptions = JSON.parse(JSON.stringify(orginalThemeColorOptions));
            localStorage.removeItem('themeColorOptions');
            resetElementPlusTheme(this.theme);
        }
    },

    getters: {
        isDarkTheme(state) {
            return state.theme === 'dark';
        },
        isLightTheme(state) {
            return state.theme === 'light';
        },
    }
})